package com.czk.api.tableExits;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Admin;
import org.apache.hadoop.hbase.client.Connection;
import org.apache.hadoop.hbase.client.ConnectionFactory;
import org.apache.hadoop.hbase.client.HBaseAdmin;

import java.io.IOException;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/6/1 17:07
 */
public class ApiTest {
    private static Connection connection = null;
    private static Admin admin = null;

    static {
        // 静态代码块初始化
        // 创建配置类
        Configuration configuration = HBaseConfiguration.create();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        //
        try {
            connection = ConnectionFactory.createConnection(configuration);
            admin = connection.getAdmin();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 关闭连接
     */
    public static void close() {
        try {
            if (admin != null) {
                admin.close();
            }
            if (connection != null) {
                connection.close();
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        }

    }

    public static void main(String[] args) throws IOException {
        //System.out.println(isTableExists("stu"));
        isTableExists_1("stu");

    }

    /**
     * 判断表是否存在
     *
     * @param tableName 表明
     * @return
     */
    public static boolean isTableExists(String tableName) throws IOException {
        // 创建配置类
        HBaseConfiguration configuration = new HBaseConfiguration();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        //
        HBaseAdmin hbaseAdmin = new HBaseAdmin(configuration);
        // 是否存在
        boolean b = hbaseAdmin.tableExists(tableName);
        // 关闭连接
        hbaseAdmin.close();
        return b;

    }

    /**
     * 新api的使用
     *
     * @param tableName
     * @return
     */
    public static boolean isTableExists_1(String tableName) throws IOException {
        // 创建配置类
        Configuration configuration = HBaseConfiguration.create();
        // zookeeper连接
        configuration.set("hbase.zookeeper.quorum", "192.168.25.133");
        // 端口
        configuration.set("hbase.zookeeper.property.clientPort", "2181");
        // 拿到连接
        Connection connection = ConnectionFactory.createConnection(configuration);
        // 拿到admin对象
        Admin admin = connection.getAdmin();
        boolean b = admin.tableExists(TableName.valueOf(tableName));
        System.out.println(b);
        return b;
    }
}
